﻿using System;
using System.Collections.Generic;

namespace TiaoTiaoCode.Common.ClassEntities
{
    /// <summary>
    /// Lambda比较表达式对象
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class TiaoTiaoLambdaComparer<T> : IEqualityComparer<T>
    {
        private readonly Func<T, T, bool> _lambdaComparer;
        private readonly Func<T, int> _lambdaHash;

        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="lambdaComparer"></param>
        public TiaoTiaoLambdaComparer(Func<T, T, bool> lambdaComparer) : this(lambdaComparer, EqualityComparer<T>.Default.GetHashCode)
        {
        }

        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="lambdaComparer"></param>
        /// <param name="lambdaHash"></param>
        /// <exception cref="ArgumentNullException"></exception>
        public TiaoTiaoLambdaComparer(Func<T, T, bool> lambdaComparer, Func<T, int> lambdaHash)
        {
            if (lambdaComparer == null)
                throw new ArgumentNullException("lambdaComparer");
            if (lambdaHash == null)
                throw new ArgumentNullException("lambdaHash");
            _lambdaComparer = lambdaComparer;
            _lambdaHash = lambdaHash;
        }

        /// <summary>
        /// 对象Equals
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        public bool Equals(T x, T y)
        {
            return _lambdaComparer(x, y);
        }

        /// <summary>
        /// 对象HashCode比较
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public int GetHashCode(T obj)
        {
            return _lambdaHash(obj);
        }
    }
}
